from django.shortcuts import redirect
from notifications.signals import notify
from .forms import MusicCommentForm, PostCommentForm
from music.models import MusicList
from post.models import PostList
from trend.models import TrendList
from django.contrib.auth.decorators import login_required

# Create your views here.
@login_required
def add_music_comment(request, mpk):
    redirect_to = request.POST.get('next', request.GET.get('next', ''))

    if request.method == 'POST':
        form = MusicCommentForm(request.POST, request.user)
        if form.is_valid():
            music = MusicList.objects.get(id=mpk)
            form.instance.music = music
            form.instance.user = request.user
            form.save()
            # 发送消息通知给音乐的作者
            notify.send(request.user, recipient=music.user, target=music,
                        verb='{}评论了你的音乐'.format(request.user.username))

            trend_content = '对音乐《%s》发表了评论'%music.name
            trend = TrendList.objects.create(user=request.user, content=trend_content)
            trend.save()

            return redirect(music)

    else:
        # form = MusicCommentForm()
        return redirect(redirect_to)


@login_required
def add_post_comment(request, ppk):
    redirect_to = request.POST.get('next', request.GET.get('next', ''))

    if request.method == 'POST':
        form = PostCommentForm(request.POST, request.user)
        if form.is_valid():
            post = PostList.objects.get(id=ppk)
            form.instance.post = post
            form.instance.user = request.user
            form.save()

            notify.send(request.user, recipient=post.user, target=post,
                        verb='{}回答了你的主题'.format(request.user.username))

            trend_content = '对主题《%s》进行了回答'%post.title
            trend = TrendList.objects.create(user=request.user, content=trend_content)
            trend.save()

            return redirect(post)

    else:
        # form = MusicCommentForm()
        return redirect(redirect_to)